/*******************************************************************************
 * Copyright (c) 2010 Mikhail Garber.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License (LGPL)
 * which accompanies this distribution
 * 
 * Contributors:
 *     Mikhail Garber - initial API and implementation
 ******************************************************************************/
package plumber.context;


import java.util.ArrayList;
import java.util.List;

import plumber.common.WorkItem;

import com.thoughtworks.xstream.XStream;

/**
 * this converter uses Xstream for external representation (string store) of FLowContext and WorkItem objects
 * @author mgarber
 *
 */
public class XStreamContextConverter implements ContextConverter {

	static XStream xs = new XStream();
	
	@Override
	public String toStorableString(FlowContext context) {
		return xs.toXML(context);
	}

	@Override
	public FlowContext contextFromStorableString(String xml) {
		if(xml == null) {
			return null;
		}
		return (FlowContext) xs.fromXML(xml);
	}

	@Override
	public WorkItem itemFromStorableString(String stored) {
		if(stored == null) {
			return null;
		}
		return (WorkItem) xs.fromXML(stored);
	}

	@Override
	public String toStorableString(WorkItem item) {
		return xs.toXML(item);
	}

	@Override
	public List<WorkItem> itemsFromStorableString(List<String> stored) {
		List<WorkItem> result = new ArrayList<WorkItem>();
		for(String string : stored) {
			result.add(this.itemFromStorableString(string));
		}
		return result;
	}

	@Override
	public List<String> toStorableStrings(List<WorkItem> items) {
		List<String> result = new ArrayList<String>();
		for(WorkItem item : items) {
			result.add(this.toStorableString(item));
		}
		return result;
	}

}
